<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/7/23
 * Time: 13:37
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Notice extends Base
{
    /**
     * 消息首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'n_type' => 1
            ];
            // 推送范围
            if(isset($params['n_range']) && $params['n_range'] != ''){
                $where['n_range'] =$params['n_range'] ;
            }
            // 推送范围
            if(isset($params['n_send']) && $params['n_send'] != ''){
                $where['n_send'] =$params['n_send'] ;
            }
            // 标题
            if(isset($params['n_title']) && $params['n_title'] != ''){
                $where['n_title'] = ['like', '%' . $params['n_title'] . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('notice')->where($where)->count();// 获取总条数
            $lists = Db::name('notice')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('n_send_datetime desc')
                ->select();
            if($lists){
                foreach($lists as $k => $v){
                    $lists[$k]['nums'] = 0;
                    if($v['n_range'] == 2){
                        $num = trim($v['n_user_id'],',');
                        $lists[$k]['nums'] = count(explode(',',$num));
                    }

                }
            }

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 发布消息
     * @return mixed|\think\response\Json
     */
    public function noticeAdd(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if($params['n_range'] == 2){
                if(trim($params['n_user_id'], ',') == ''){
                    return json(['code' => 100, 'msg' => "推送用户不能为空"]);
                }
            }

            $time = date('Y-m-d H:i:s');
            $data = [
                'n_title' => trim($params['n_title'], ' '), // 标题
                'n_content' => trim($params['n_content'], ' '),// 内容
                'n_type' => 1,// 内容
                'n_range' => $params['n_range'],//推送范围  1 全部  2 个别
                'n_read_user_id' => ',0,', // 已读用户
                'n_del_user_id' => ',0,', // 删除的用户
                'n_send_datetime' => $time, // 推送时间
                'n_auto' => $params['n_auto'],
            ];
            if($params['n_auto'] == 2){
                $data['n_send'] = 1;
                $data['n_auto_time'] = $params['n_auto_time'];
                if($params['n_auto_time'] <= $time){
                    return json(['code' => 100, 'msg' => "推送时间不能小于当前时间"]);
                }
            }
            if($params['n_range'] == 1){
                $data['n_user_id'] = 0;
                $ids = Db::table('up_u_user')
                    ->where('user_status',1)
                    ->where('user_id','<>',0)
                    ->column('user_id');
            }else{
                $data['n_user_id'] = ',' . $params['n_user_id'] . ',';
                $ids = explode(',', trim($data['n_user_id'], ','));
            }
            $res = Db::table('up_notice')->insertGetId($data);

            if($res){
                if($params['n_auto'] == 1) { //立即推送类型的才走这个
                    $list = [];//需要推送的用户数组
                    foreach ($ids as $k => $v) {
                        $val = (string)$v;
                        array_push($list, $val);
                    }
                    try {
                        $this->Jpush(1, $list, $params['n_title'], ['nid' => $res, 'type' => 1]);
                    } catch (\Exception $e) {
                    }
                }
                return json(['code' => 200, 'msg' => '发布成功']);
            }else{
                return json(['code' => 100, 'msg' => '发布失败']);
            }
        }
        //所有用户
        $user = Db::table('up_u_user')
            ->field('user_id, user_username,user_phone')
            ->where('user_status', 1)
            ->select();
        $this->assign([
            'user' => $user
        ]);
        return $this->fetch('notice/noticeadd');
    }
    /**
     * 发送
     * @return mixed|\think\response\Json
     */
    public function noticeSend(){
        $n_id = input('id');
        $info = Db::name('notice')
            ->where('n_id', $n_id)
            ->find();
        if($info['n_send'] == 2){
            return json(['code' => 100, 'msg' => '此条消息已推送！']);
        }
        if($info['n_range'] == 1){
            $ids = Db::table('up_u_user')
                ->where('user_status',1)
                ->where('user_id','<>',0)
                ->column('user_id');
        }else{
            $ids = explode(',', trim($info['n_user_id'], ','));
        }
        $res = Db::name('notice')->where('n_id', $n_id)->update([
            'n_send' => 2,
            'n_auto_time' => date('Y-m-d H:i:s')
        ]);
        if($res){
            $list = [];//需要推送的用户数组
            foreach ($ids as $k => $v) {
                $val = (string)$v;
                array_push($list, $val);
            }
            try {
                $this->Jpush(1, $list, $info['n_title'], ['nid' => $n_id, 'type' => 1]);
            } catch (\Exception $e) {
            }
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }
    
    /**
     * 消息详情
     * @return mixed
     */
    public function noticeDetail(){
        $n_id = input('n_id');
        $info = Db::name('notice')
            ->where('n_id', $n_id)
            ->find();
        if(Request::instance()->isPost()){
            $params = input('param.');
            if($params['n_range'] == 2){
                if(trim($params['n_user_id'], ',') == ''){
                    return json(['code' => 100, 'msg' => "推送用户不能为空"]);
                }
            }

            $time = date('Y-m-d H:i:s');
            $data = [
                'n_title' => trim($params['n_title'], ' '), // 标题
                'n_content' => trim($params['n_content'], ' '),// 内容
                'n_type' => 1,// 内容
                'n_range' => $params['n_range'],//推送范围  1 全部  2 个别
                'n_read_user_id' => ',0,', // 已读用户
                'n_del_user_id' => ',0,', // 删除的用户
                'n_send_datetime' => $time, // 推送时间
                'n_auto' => $params['n_auto'],
            ];
            if($params['n_auto'] == 2){
                $data['n_send'] = 1;
                $data['n_auto_time'] = $params['n_auto_time'];
                if($params['n_auto_time'] <= $time){
                    return json(['code' => 100, 'msg' => "推送时间不能小于当前时间"]);
                }
            }else{
                $data['n_send'] = 2;
            }
            if($params['n_range'] == 1){
                $data['n_user_id'] = 0;
                $ids = Db::table('up_u_user')
                    ->where('user_status',1)
                    ->where('user_id','<>',0)
                    ->column('user_id');
            }else{
                $data['n_user_id'] = ',' . $params['n_user_id'] . ',';
                $ids = explode(',', trim($data['n_user_id'], ','));
            }
            $res = Db::table('up_notice')->where('n_id',$n_id)->update($data);
            if($res){
                if($params['n_auto'] == 1) { //立即推送类型的才走这个
                    $list = [];//需要推送的用户数组
                    foreach ($ids as $k => $v) {
                        $val = (string)$v;
                        array_push($list, $val);
                    }
                    try {
                        $this->Jpush(1, $list, $params['n_title'], ['nid' => $n_id, 'type' => 1]);
                    } catch (\Exception $e) {
                    }
                }
                return json(['code' => 200, 'msg' => '发布成功']);
            }else{
                return json(['code' => 100, 'msg' => '发布失败']);
            }
        }
        $info['n_user_id'] = explode(',',trim($info['n_user_id'],','));
        //所有用户
        $user = Db::table('up_u_user')
            ->field('user_id, user_username,user_phone')
            ->where('user_status', 1)
            ->select();
        $this->assign([
            'user' => $user
        ]);
        $this->assign('info' , $info);
        return $this->fetch('notice/noticedetail');
    }
    
    /**
     * 发布的用户列表
     * @return mixed|\think\response\Json
     */
    public function noticeUser(){
        if(request()->isAjax ()){
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $user_ids = Db::table('up_notice')->where('n_id', session('n_id'))->value('n_user_id');
            $where['user_id'] = ['IN', trim($user_ids, ',')];
            $count = Db::name('u_user')->where($where)->count();// 获取总条数
            $lists = Db::name('u_user')
                ->field('user_username, user_image, user_id,user_phone')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('user_time desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $n_id = input('n_id');
        session('n_id', $n_id);
        return $this->fetch('notice/noticeuser');
    }
    
    /**
     * 删除消息
     * @return \think\response\Json
     */
    public function noticeDel(){
        $n_id = input('id');
        $res = Db::table('up_notice')->delete($n_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    

}